package com.ftg.learn.chapter10.base02.util;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * @author 布衣
 */
public class BaseUtil {

    public static SqlSession sqlSession = null;

    /**
     * 创建sqlsession
     */
    public static void getSqlSession() {
        Configuration config = new Configuration();

        config.setLogImpl(Slf4jImpl.class);
        config.setLazyLoadingEnabled(true);
        //拦截器
        config.addInterceptor(new com.github.pagehelper.PageInterceptor());

        TransactionFactory transactionFactory = new JdbcTransactionFactory();

        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        dataSource.setURL("jdbc:mysql://localhost:3306/exam");

        Environment env = new Environment("dev", transactionFactory, dataSource);

        //给环境提供信息，用于连接数据 库
        config.setEnvironment(env);

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(config);
        sqlSession = sqlSessionFactory.openSession();

        sqlSession.getConfiguration().addMappers("com.ftg.learn.chapter10.base02");
    }

    public static <E> E getBean(Class<E> e1) {
        if (sqlSession == null) {
            getSqlSession();
        }
        return sqlSession.getMapper(e1);
    }

    public static SqlSession GetInstance() {
        return sqlSession;

    }

}
